#!/bin/sh
[ "$1" = --First ] && A=Y || A=N
# 防止重复启动
[ -f /var/lock/bypass.lock -a $A = N ] && exit 1
LOCK=/var/lock/bypass-update.lock
[ -f $LOCK ] && exit 1
touch $LOCK
DIR=/usr/share/bypass
T_FILE=/etc/bypass

log(){
	echo "$(date +'%Y-%m-%d %H:%M:%S') $*" >> /var/log/bypass.log
}

C=$(uci -q get bypass.@global[0].run_mode)

mkdir -p $T_FILE 2>/dev/null
if [ "$C" = router ];then
	if [ ! -f $T_FILE/china.txt ];then
		while ! (curl -kLfsm 5 -o /tmp/china.txt https://fastly.jsdelivr.net/gh/kiddin9/china_ip_list@main/china_ip_list.txt);do
			sleep 1
		done
	else
		curl -kLfsm 5 -o /tmp/china.txt https://fastly.jsdelivr.net/gh/kiddin9/china_ip_list@main/china_ip_list.txt
	fi
	[[ -f /tmp/china.txt && $? == 0 ]] && {
	if ! cmp -s /tmp/china.txt $T_FILE/china.txt;then
		log "China IPv4 List 已更新"
		cp -f /tmp/china.txt $T_FILE/china.txt
		[ $A = N ] && ipset list china_v4 >/dev/null 2>&1 && $DIR/chinaipset
	fi
	}

	if [ ! -f $T_FILE/china_v6.txt ];then
		while ! (curl -kLfsm 3 -o /tmp/china_v6.txt https://ispip.clang.cn/all_cn_ipv6.txt);do
			sleep 1
		done
	elif [ $A = N ];then
		curl -kLfsm 3 -o /tmp/china_v6.txt https://ispip.clang.cn/all_cn_ipv6.txt
	fi
	[[ -f /tmp/china_v6.txt && $? == 0 ]] && {
	if ! cmp -s /tmp/china_v6.txt $T_FILE/china_v6.txt;then
		log "China IPv6 List 已更新"
		cp -f /tmp/china_v6.txt $T_FILE/china_v6.txt
		[ $A = N ] && ipset list china_v6 >/dev/null 2>&1 && $DIR/chinaipset v6
	fi
	}
fi

if [ "$C" = gfw -o "$(uci -q get bypass.@global[0].gfw_mode)" = 1 ];then
	if [ ! -f $T_FILE/gfw.list ];then
		while ! (curl -kLfsm 5 -o /tmp/gfw.b64 https://fastly.jsdelivr.net/gh/gfwlist/gfwlist/gfwlist.txt);do
			sleep 1
		done
	elif [ "$C" = gfw -o $A = N ];then
		curl -kLfsm 5 -o /tmp/gfw.b64 https://fastly.jsdelivr.net/gh/gfwlist/gfwlist/gfwlist.txt
	fi
	if [[ -f /tmp/gfw.b64 && $? == 0 ]];then
	$DIR/by-gfw
	if ! cmp -s /tmp/gfwnew.txt $T_FILE/gfw.list;then
		cp -f /tmp/gfwnew.txt $T_FILE/gfw.list
		log "GFW List 已更新"
	fi
	fi
fi

rm -f $LOCK /tmp/china*.txt /tmp/gfwnew.txt

[ $A = Y ] && /etc/init.d/bypass start updated &
